<template>
  <div class="search-container">
    <!-- 搜索栏 -->
    <form class="search-form" action="/">
      <van-search
        v-model="searchText"
        show-action
        placeholder="请输入搜索关键词"
        background="#3296fa"
        @search="onSearch"
        @cancel="onCancel"
        @focus="isShow = false"
      />
    </form>
    <!-- 搜索结果 -->
    <search-result v-if="isShow" :searchText="searchText" />
    <!-- /搜索结果 -->

    <!-- 联想建议 -->
    <search-suggestion
      v-else-if="searchText"
      :searchText="searchText"
      @search="onSearch"
    />
    <!-- /联想建议 -->

    <!-- 搜索历史记录 -->
    <search-history
      v-else
      :SearchHistory="SearchHistory"
      @allRemove="SearchHistory = []"
      @search="onSearch"
    />
    <!-- /搜索历史记录 -->
  </div>
</template>

<script>
import SearchHistory from './components/search-history'
import SearchSuggestion from './components/search-suggestion'
import SearchResult from './components/search-result'
import { setItem, getItem } from '../../utils/storage'
export default {
  data() {
    return {
      searchText: '',
      isShow: false,
      // 数据初始化的时候就获取到数据渲染出来 本地有数据句渲染数据,没有的话就返回一个空数组,不然会报错
      SearchHistory: getItem('SEARVH-HISTORY') || []
    }
  },
  watch: {
    // 当数组里面的数据发生改变的时候,就把他存到本地存储中
    SearchHistory(val) {
      setItem('SEARVH-HISTORY', val)
    }
  },
  methods: {
    // onsarch有三个触发事件:1.当点击历史记录的时候触发,2.按下回车的时候触发,3.点击搜索建议的时候触发
    onSearch(val) {
      this.searchText = val
      // 存储历史记录 判断是否有重复的数据的
      const index = this.SearchHistory.indexOf(val)
      if (index !== -1) {
        this.SearchHistory.splice(index, 1)
      }
      // 把获取到的新数据添加到最前面
      this.SearchHistory.unshift(val)
      this.isShow = true
    },
    onCancel() {
      this.$router.back()
    }
  },
  components: {
    SearchHistory,
    SearchSuggestion,
    SearchResult
  }
}
</script>

<style lang="less" scoped>
.search-container {
  padding-top: 108px;
  .van-search__action {
    color: #fff;
  }
  .search-form {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    z-index: 1;
  }
}
</style>
